/* eslint-disable max-lines */
/* eslint-disable eqeqeq */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import myStyle from './fenzi.less';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Popconfirm, TreeSelect, message, Form } from 'antd';
import { SelectC, ModalC, PrimaryC, PrimaryGhostC, InputC, TreeSelectC } from '../../../components';
import dictData from './config';
import { formSelectData, formatDictData } from '../../../utils/utils';
import CardTreeListC from './cardTreeList';

const { SHOW_ALL } = TreeSelect;

class AddFenzi extends PureComponent {
  state = {
    controlValueType: 1, // 控制类别显示的是什么 0:是否下拉，1:树形下拉 ，2:输入框
    cLeveType: '',
    components: [], // 公式下面的 关系公式 树形结构
    conditionBoundList: [], // 证券类型下拉
    conditionOrigin: [], // 证券类型原始数据
    controlValuesList: [], // 控制类别下拉数据
    compareMethodList: [], // 比较方向下拉
    RiskIndexInfo: [],
    currentNode: undefined, // 点击树节点 存储节点的数据
    showTemplate: false, // 展示模板名称编辑弹窗
    templateObj: undefined, // 当前正在保存的模板
    templatelist: [], // 模板下拉
    currentTemp: undefined, // 当前选择的模板名称
    productData: [], // 产品范围
    myChild: [], // 控制方式对应的配置
  };

  formRef = React.createRef(); // 页面所见的表单

  formRef01 = React.createRef(); // 弹窗保存名称表单

  componentDidMount() {
    const { detailData = {} } = this.props;

    this.searchFactorAndCondition(detailData.indexCategory || '-1'); // 默认指标分类 全部  查询证券类型
    this.settingField('indexCategory', detailData.indexCategory || '-1');
    if (detailData.riskFactorNo) {
      this.riskFactorNoChange(detailData.riskFactorNo.toString(), 'detail');
    }
    this.setState({
      components: detailData.conditionList || [],
    });
    // 查询模板列表
    this.queryTemplateList();
  }

  // 查询证券类型下拉   flag回填时调用
  searchFactorAndCondition = (value, id) => {
    const { dispatch } = this.props;
    const { resetFields } = this.formRef.current;
    if (!id) resetFields(['controlValue', 'conditionBoundNo', 'compareMethod']);
    // 获取证券类型下拉
    dispatch({
      type: 'limitSetting/queryConditionByFactorCode',
      payload: {
        indexCateCode: value,
      },
    }).then((res) => {
      if (res && res.success) {
        let arr = [];
        if (res.data) {
          arr = res.data.map((item) => {
            return {
              title: item.boundName,
              value: item.boundNo.toString(),
            };
          });
        }
        // 查询证券类型下拉
        this.setState({
          conditionOrigin: res.data || [],
          conditionBoundList: arr,
        });
        if (id) {
          // 公式回填查询数据
          this.onChangeCondition(id, 'type');
        }
      }
    });
  };

  // 确定 保存在前台数据
  onOK = async (type) => {
    const { validateFields } = this.formRef.current;
    let query;
    const { myChild } = this.state;
    const temp = ['indexName', 'riskFactorNo', 'indexSymbol', 'indexCatcode'];
    const arr = temp.concat(myChild);
    const values = await validateFields(arr);
    console.log(values, '*****');
    if (values) {
      const params = {
        ...values,
        appliedProductIds: values.appliedProductIds ? [values.appliedProductIds] : undefined,
        indexId: this.props.detailData ? this.props.detailData.indexId : new Date().getTime(),
        indexPosition: this.props.indexPosition, // 分子1还是分母2
        // indexSeq: Number(1),//无法知道含义
        indexSymbol: Number(values.indexSymbol),
        riskFactorNo: Number(values.riskFactorNo),
      };

      const conditionList = this.state.TreeList.state.components;
      // 增加indexCategory参数
      const formatData = (arr) => {
        if (arr?.length) {
          arr.map((x) => {
            x.indexCategory = x.indexCategory ?? '-1';
            x.conditionList?.map((item) => {
              item.indexCategory = item.indexCategory ?? '-1';
              if (item.conditionList?.length) formatData(item);
            });
          });
        }
      };

      params.conditionList = conditionList || [];

      console.log(params.conditionList);
      if (type == 'template') {
        // 模板保存的校验
        query = params;
      } else {
        this.props.onOK(params); // 将当前分子数据传给父组件
      }
    } else if (type == 'template') {
      // 模板保存的校验
      message.warning('请检查必填项！');
    }

    return query;
  };

  // 证券类型变更 清空 比较方向 控制类别
  onChangeCondition = (e, type) => {
    const { resetFields } = this.formRef.current;
    const { conditionOrigin } = this.state;
    if (!type) resetFields(['compareMethod', 'controlValue', 'controlValueName']);
    const arr = conditionOrigin.filter((item) => item.boundNo == e);
    console.log(arr);
    if (arr.length) {
      // 获取比较方向的下拉 以及控制类别的展示形式 及下拉
      this.setState({
        compareMethodList: arr[0].compareMethod == 0 ? dictData.directionList : dictData.directionList.filter((item) => item.value > 4),
        controlValueType: arr[0].controlValueType,
      });
      // 获取关系运算符右侧的下拉
      this.props
        .dispatch({
          type: 'limitSetting/queryConditionByIndexClassInfo',
          payload: {
            controlScope: arr[0].controlScope,
            boundName: arr[0].boundName,
          },
        })
        .then((res) => {
          if (res && res.success) {
            this.setState({
              controlValuesList: res.data || [],
            });
          } else {
            this.setState({
              controlValuesList: [],
            });
          }
        });
    } else {
      this.setState({
        compareMethodList: [],
        controlValueType: 1,
        controlValuesList: [],
      });
    }
  };

  // 添加关系
  addRelation = () => {
    const { getFieldsValue } = this.formRef.current;
    const params = getFieldsValue(['joinTypeMode', 'controlValue', 'conditionBoundNo', 'compareMethod']);
    this.state.TreeList.addRelation(params); // 调用子组件新增关系函数
  };

  // 修改公式节点
  addExpression = (type) => {
    const { validateFields, getFieldsValue } = this.formRef.current;
    validateFields(['indexCategory', 'joinTypeMode', 'controlValue', 'conditionBoundNo', 'compareMethod']).then((values) => {
      values.controlValueName = getFieldsValue(['controlValueName']).controlValueName;
      console.log(values);
      if (type == 'add') this.state.TreeList.addExpression(values);
      if (type == 'edit') this.state.TreeList.editExpression(values);
    });
  };

  // 控制类别下拉 转化成树形结构
  changeTreeData = (data) => {
    const arr = [];
    if (data)
      data.map((item) => {
        const newData = {};
        newData.title = item.itemDesc;
        newData.key = item.value;
        newData.value = item.value;
        newData.children = item.children ? this.changeTreeData(item.children) : '';
        arr.push(newData);
      });
    return arr;
  };

  // 模板切换 重新渲染分子的所有数据
  onChangeTemp = (e) => {
    const { templatelist } = this.state;
    this.settingField('templateId', e);
    if (e) {
      templatelist.map((item) => {
        if (item.value == e) {
          item.indexCategory = '-1';
          this.setValue(item);
          this.setState({
            currentTemp: { value: item.value, title: item.title },
          });
        }
      });
    } else {
      this.setState({
        currentTemp: undefined,
      });
    }
  };

  // 渲染分子表单
  setValue = (obj) => {
    const { setFieldsValue } = this.formRef.current;
    if (!obj) return;
    this.riskFactorNoChange(obj.riskFactorNo.toString(), 'detail');
    setTimeout(() => {
      setFieldsValue({
        indexSymbol: obj.indexSymbol?.toString(),
        indexName: obj.indexName,
        riskFactorNo: obj.riskFactorNo?.toString(),
        indexCategory: obj.indexCategory,
        groupTypes: obj.groupTypes,
        appliedProductIds: obj.appliedProductIds?.join(','),
        dayOffset: obj.dayOffset,
        assignWeightsType: obj.assignWeightsType,
        fundAndAssetPlanValueRatio: obj.fundAndAssetPlanValueRatio,
        priceSource: obj.priceSource,
      });
    }, 300);
    this.setState({
      components: obj.conditionList || [],
    });
  };

  // 通过对应的计算因子 找到对应的因子配置
  findFactorItem = (e) => {
    const {
      limitSetting: { Factor },
    } = this.props;
    const findGroupTypes = (array) => {
      for (let index = 0; index < array.length; index++) {
        const item = array[index];
        if (item.value == e) {
          obj = item;
        }
        if (item.children?.length) {
          findGroupTypes(item.children);
        }
      }
    };
    let obj = {};
    findGroupTypes(Factor);
    return obj;
  };

  // 找到对应的下拉数据
  findSelectList = (dictData, list) => {
    const arr = []; // 存储下拉
    formSelectData(dictData).map((item) => {
      list.map((x) => {
        if (item.value == x) {
          arr.push(item);
        }
      });
    });
    return arr;
  };

  // 计算因子变更
  riskFactorNoChange = (e, type) => {
    // 通过对应的计算因子 找到对应的因子配置 并判断是否有对应的下拉，并且返回对应的下拉格式
    const {
      limitSetting: { dictMap = {} },
    } = this.props;
    const { RiskOptionCnName = [] } = dictMap;
    const item = this.findFactorItem(e);
    this.setState({
      myChild: [],
    });
    const myChild = [];
    // 判断是否由控制方式默认值或者是否有控制方式下拉 有的话就展示控制方式
    if (item?.defaultGroupType || item?.relatedGroupType?.length) {
      // 控制方式
      // 判断有无默认值defaultGroupType 有的话下就是这个值了
      const relatedGroupType = item.defaultGroupType ? [item.defaultGroupType] : item.relatedGroupType;
      const mySelect = this.findSelectList(dictMap.RiskGroupType, relatedGroupType);
      myChild.push('groupTypes');
      this.setState(
        {
          riskGroupType: mySelect,
          myChild: [...myChild],
          groupTypesRequired: !!item?.defaultGroupType,
        },
        () => {
          if (item?.defaultGroupType)
            this.formRef.current.setFieldsValue({
              groupTypes: relatedGroupType,
            });
        },
      );
    }

    if (item?.priceSourceOption?.length) {
      // 价格来源
      const mySelect2 = this.findSelectList(RiskOptionCnName, item?.priceSourceOption);
      myChild.push('priceSource');
      this.setState({
        priceSourceOptionList: mySelect2,
        myChild: [...myChild],
      });
    }
    if (item?.fundAndAssetPlanValueRatioOption?.length) {
      // 基金和资管计划市值
      const mySelect0 = this.findSelectList(RiskOptionCnName, item?.fundAndAssetPlanValueRatioOption);
      myChild.push('fundAndAssetPlanValueRatio');
      this.setState({
        fundAndAssetPlanValueRatioOptionList: mySelect0,
        myChild: [...myChild],
      });
    }
    if (item?.assignWeightsTypeOption?.length) {
      myChild.push('assignWeightsType');
      // 加权方式
      const mySelect1 = this.findSelectList(RiskOptionCnName, item?.assignWeightsTypeOption);
      this.setState({
        assignWeightsTypeList: mySelect1,
        myChild: [...myChild],
      });
    }
    if (item?.productIdOption?.length) {
      // 产品范围
      myChild.push('appliedProductIds');
      const mySelect = this.findSelectList(RiskOptionCnName, item?.productIdOption);
      this.setState({
        productData: mySelect,
        myChild: [...myChild],
      });
    }
    if (item?.dayOffsetOption?.length) {
      // 偏移天数
      myChild.push('dayOffset');
      const mySelect = this.findSelectList(RiskOptionCnName, item?.dayOffsetOption);
      this.setState({
        dayOffsetList: mySelect,
        myChild: [...myChild],
      });
    }
    if (type == 'detail') return;
    this.formRef.current.setFieldsValue({
      groupTypes: undefined,
      appliedProductIds: undefined,
      dayOffset: undefined,
      assignWeightsType: undefined,
      fundAndAssetPlanValueRatio: undefined,
      priceSource: undefined,
    });
  };

  // 最右侧select下拉的数据
  onChangeSelect = (e, option) => {
    this.formRef.current.setFieldsValue({
      controlValueName: option?.props?.children,
    });
  };

  //
  onChangeTreeSelect = (e, option) => {
    this.formRef.current.setFieldsValue({
      controlValueName: option,
    });
  };

  // 赋值表单值
  settingField = (field, val) => {
    this.setState({
      [field]: val,
    });
  };

  renderTopForm = () => {
    const {
      loading,
      detailData = {},
      limitSetting: { dictMap = {}, Factor },
    } = this.props;
    const {
      myChild = [],
      assignWeightsTypeList = [],
      priceSourceOptionList = [],
      dayOffsetList = [],
      fundAndAssetPlanValueRatioOptionList = [],
      currentNode,
      conditionBoundList,
      compareMethodList,
      controlValuesList,
      controlValueType,
      productData = [],
    } = this.state;
    let treeData = [];
    if (controlValueType == 1) {
      treeData = this.changeTreeData(controlValuesList);
    }
    return (
      <Form ref={this.formRef} labelWrap={true}>
        <div className={myStyle.topCls}>
          <div>
            <SelectC
              form={this.formRef.current}
              dataIndex='indexSymbol'
              title='符号'
              initialValue={detailData.indexSymbol || '1'}
              dataSource={dictData.shiftMethod}
              // allowClear
            />
          </div>
          <div>
            <InputC
              form={this.formRef.current}
              dataIndex='indexName'
              title='指标名称'
              initialValue={detailData.indexName || undefined}
              rules={[{ required: true, message: '指标名称不能为空' }]}
            />
          </div>
          <div>
            <div>
              <SelectC
                form={this.formRef.current}
                dataIndex='templateId'
                title='模板选择'
                initialValue={detailData.templateId || undefined}
                dataSource={this.state.templatelist}
                allowClear={true}
                onChange={this.onChangeTemp}
                optionTitle={true}
              />
            </div>
            <div>
              <PrimaryGhostC title='保存' onClick={() => this.saveTemplate('save')} disabled={!this.state.templateId == true} />
              <PrimaryGhostC title='另存为' onClick={() => this.saveTemplate('saveAs')} />
              <Popconfirm
                title={'确定删除？'}
                icon={<ExclamationCircleOutlined />}
                onConfirm={() => {
                  this.deleteTemplate();
                }}
              >
                <PrimaryGhostC title='删除' disabled={!this.state.templateId == true} loading={loading.effects['limitSetting/deleteTemplate'] == true} />
              </Popconfirm>
            </div>
          </div>
          <div>
            <div>
              <TreeSelectC
                form={this.formRef.current} // form对象
                title='计算因子'
                dataIndex='riskFactorNo' // Form识别的Item ID
                dataSource={Factor}
                treeDefaultExpandAll={true}
                showCheckedStrategy={SHOW_ALL}
                rules={[{ required: true, message: '计算因子不能为空' }]}
                initialValue={detailData.riskFactorNo ? detailData.riskFactorNo.toString() : undefined}
                onChange={this.riskFactorNoChange}
              />
            </div>
          </div>
          <div>
            <div className={myChild.includes('priceSource') || myChild.includes('fundAndAssetPlanValueRatio') ? 'labalWrap' : ''}>
              {myChild.includes('groupTypes') ? (
                <SelectC
                  form={this.formRef.current}
                  dataIndex='groupTypes'
                  title='控制方式'
                  isMultiple={true}
                  allowClear={!this.state.groupTypesRequired}
                  initialValue={detailData.groupTypes ? detailData.groupTypes : undefined}
                  dataSource={this.state.riskGroupType || []}
                  rules={[{ required: this.state.groupTypesRequired == true, message: '请选择控制方式' }]}
                />
              ) : null}
              {myChild.includes('appliedProductIds') ? (
                <SelectC
                  form={this.formRef.current}
                  title='产品范围'
                  dataIndex='appliedProductIds'
                  initialValue={detailData.appliedProductIds ? detailData.appliedProductIds.join(',') : undefined}
                  filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  showSearch={true}
                  dataSource={productData}
                  allowClear={true}
                />
              ) : null}
              {myChild.includes('dayOffset') ? (
                <SelectC
                  form={this.formRef.current}
                  dataIndex='dayOffset'
                  title='偏移天数'
                  initialValue={detailData.dayOffset ? detailData.dayOffset : undefined}
                  dataSource={dayOffsetList}
                  allowClear={true}
                  // rules={[{ required: true, message: '请选择偏移天数' }]}
                />
              ) : null}

              {myChild.includes('priceSource') ? (
                <SelectC
                  form={this.formRef.current}
                  dataIndex='priceSource'
                  title='债券价格来源'
                  initialValue={detailData.priceSource ? detailData.priceSource : undefined}
                  dataSource={priceSourceOptionList}
                  rules={[{ required: true, message: '请选择债券价格来源' }]}
                />
              ) : null}
              {myChild.includes('fundAndAssetPlanValueRatio') ? (
                <SelectC
                  form={this.formRef.current}
                  dataIndex='fundAndAssetPlanValueRatio'
                  title='基金和资管计划市值'
                  initialValue={detailData.fundAndAssetPlanValueRatio ? detailData.fundAndAssetPlanValueRatio : undefined}
                  dataSource={fundAndAssetPlanValueRatioOptionList}
                  rules={[{ required: true, message: '请选择基金和资管计划市值' }]}
                />
              ) : null}
              {myChild.includes('assignWeightsType') ? (
                <SelectC
                  form={this.formRef.current}
                  dataIndex='assignWeightsType'
                  title='加权方式'
                  initialValue={detailData.assignWeightsType ? detailData.assignWeightsType : undefined}
                  dataSource={assignWeightsTypeList}
                  allowClear={true}
                  // rules={[{ required: true, message: '请选择加权方式' }]}
                />
              ) : null}
            </div>
          </div>
          <div>
            <div>
              <SelectC
                form={this.formRef.current}
                dataIndex='joinTypeMode'
                title='关联规则'
                initialValue={detailData.joinTypeMode ? detailData.joinTypeMode : '1'}
                dataSource={dictData.joinTypeMode}
              />
            </div>
            <div>
              <PrimaryC title='添加关系' onClick={this.addRelation} />
            </div>
          </div>
          <div>
            {/* 指标分类 */}
            <div>
              <SelectC
                form={this.formRef.current}
                dataIndex='indexCategory'
                onChange={(e) => {
                  this.searchFactorAndCondition(e);
                  this.settingField('indexCategory', e);
                }}
                initialValue={detailData.indexCategory ? detailData.indexCategory : '-1'}
                dataSource={dictMap.index_category ? formatDictData(dictMap.index_category) : []}
                rules={[{ required: true, message: '指标分类必填' }]}
              />
            </div>
            <div>
              {/* 证券类型 */}
              <SelectC
                form={this.formRef.current}
                dataIndex='conditionBoundNo'
                dataSource={conditionBoundList || []}
                onChange={(e, _option) => {
                  this.onChangeCondition(e);
                  this.settingField('conditionBoundNo', e);
                }}
                disabled={this.state.indexCategory == undefined}
                rules={[{ required: true, message: '证券类型必填' }]}
              />
            </div>
            {/* 比较方向  根据证券类型变化 */}
            <div>
              <SelectC
                form={this.formRef.current}
                dataIndex='compareMethod'
                initialValue={detailData.compareMethod !== undefined ? detailData.compareMethod.toString() : undefined}
                dataSource={compareMethodList}
                disabled={this.state.conditionBoundNo == undefined}
                rules={[{ required: true, message: '方向必填' }]}
              />
            </div>
            {/* 控制类别 */}
            <div>
              {controlValueType == 0 ? (
                <SelectC
                  form={this.formRef.current}
                  dataIndex='controlValue'
                  initialValue={undefined}
                  dataSource={controlValuesList.map((item) => {
                    return { title: item.itemName, value: item.value };
                  })}
                  disabled={this.state.conditionBoundNo == undefined}
                  rules={[{ required: true, message: '控制类别必填' }]}
                  onChange={this.onChangeSelect}
                />
              ) : null}
              {controlValueType == 1 ? (
                <TreeSelectC
                  form={this.formRef.current} // form对象
                  dataIndex='controlValue' // Form识别的Item ID
                  dataSource={treeData}
                  isMultiple={true}
                  treeCheckable={true}
                  treeDefaultExpandAll={true}
                  showCheckedStrategy={SHOW_ALL}
                  disabled={this.state.conditionBoundNo == undefined}
                  rules={[{ required: true, message: '控制类别必填' }]}
                  onChange={this.onChangeTreeSelect}
                />
              ) : null}
              {controlValueType == 2 ? (
                <InputC
                  form={this.formRef.current}
                  dataIndex='controlValue'
                  disabled={this.state.conditionBoundNo == undefined}
                  rules={[{ required: true, message: '控制类别必填' }]}
                />
              ) : null}
              <div style={{ display: 'none' }}>
                <InputC form={this.formRef.current} dataIndex='controlValueName' />
              </div>
            </div>
            <div>
              <PrimaryGhostC title='保存' disabled={!currentNode} onClick={() => this.addExpression('edit')} />
              <PrimaryC title='新建' onClick={() => this.addExpression('add')} />
            </div>
          </div>
        </div>
      </Form>
    );
  };

  // 保存模板 直接保存至后端 无需点击确定按钮
  saveTemplate = async (type) => {
    const query = await this.onOK('template');
    console.log(query, 'query');
    if (!query) {
      return;
    }
    this.setState(
      {
        templateObj: query,
      },
      () => {
        if (type == 'save') {
          // 保存
          const params = { ...this.state.templateObj, demoName: this.state.currentTemp.title, demoId: this.state.currentTemp.value };
          this.saveTemp(params, 'limitSetting/addTemplate'); // 保存至后端
        } else {
          // 另存为
          this.setState({
            showTemplate: true,
          });
        }
      },
    );
  };

  // 删除模板
  deleteTemplate = () => {
    const { dispatch } = this.props;
    const { getFieldValue, setFieldsValue } = this.formRef.current;
    dispatch({
      type: 'limitSetting/deleteTemplate',
      payload: { demoId: getFieldValue('templateId') },
      callback: () => {
        this.queryTemplateList(); // 重新查询下拉并定位到对应数据
        setFieldsValue({
          templateId: undefined,
        });
        this.setState({ currentTemp: undefined });
        this.settingField('templateId', undefined);
      },
    });
  };

  // 查询模板列表
  queryTemplateList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'limitSetting/queryTemplateList',
      payload: {},
      callback: (data) => {
        data?.map((item) => {
          item.value = item.demoId;
          item.title = item.demoName;
        });
        this.setState({
          templatelist: data || [],
        });
      },
    });
  };

  // 获取到回填form公式数据
  getCurrentNode = (obj) => {
    const { getFieldValue, setFieldsValue } = this.formRef.current;
    console.log(obj, '当前node');

    if (!obj) {
      this.setState({ currentNode: obj });
      return; // 无选中子节点
    }
    if (obj && obj.conditionBoundNo == '') return; // 证券类型未选
    this.setState(
      {
        currentNode: obj,
        controlValueType: obj.controlValueType,
      },
      () => {
        if (obj.indexCategory != getFieldValue('indexCategory')) this.searchFactorAndCondition('-1', obj.conditionBoundNo.toString());
        else if (obj.conditionBoundNo != getFieldValue('conditionBoundNo')) {
          this.onChangeCondition(obj.conditionBoundNo, 'type');
        }
        setFieldsValue({
          indexCategory: obj.indexCategory ?? '-1',
          joinTypeMode: obj.joinTypeMode.toString(),
          conditionBoundNo: obj.conditionBoundNo ? obj.conditionBoundNo.toString() : obj.conditionBoundNo,
          compareMethod: obj.compareMethod.toString(),
          controlValue: obj.controlValue ? obj.controlValue : undefined,
          controlValueName: obj.controlValueName?.indexOf('[') > -1 ? JSON.parse(obj.controlValueName) : obj.controlValueName,
        });
        this.settingField('indexCategory', obj.indexCategory ?? '-1');
        this.settingField('conditionBoundNo', obj.conditionBoundNo ? obj.conditionBoundNo.toString() : obj.conditionBoundNo);
      },
    );
  };

  // 保存名称即新增
  saveTemplateName = () => {
    const { validateFields } = this.formRef01.current;
    validateFields(['templateName']).then((values) => {
      if (!this.state.templateObj) return;
      const params = { ...this.state.templateObj, demoName: values.templateName };
      this.saveTemp(params, 'limitSetting/addTemplate'); // 保存至后端
    });
    // .catch((err) => {
    //   console.log(err);
    // });
  };

  // 模板保存至后端
  saveTemp = (params, url) => {
    this.props.dispatch({
      type: url,
      payload: {
        ...params,
      },
      callback: () => {
        this.setState({
          showTemplate: false,
        });
        this.queryTemplateList(); // 重新查询下拉并定位到对应数据
      },
    });
  };

  // 取消模板名称的保存
  cancelTemplate = () => {
    this.setState({
      showTemplate: false,
    });
  };

  render() {
    const { detailData, visible, indexPosition, loading } = this.props;
    const title = indexPosition == '1' ? '分子' : '分母';
    const modalProps = {
      visible,
      onOk: this.onOK,
      onCancel: () => {
        this.props.onCancel();
      },
      title: detailData ? `${title}设置-编辑` : `${title}设置-新增`,
      className: myStyle.AddFenzi,
      width: 1000,
      maskClosable: false,
    };
    const modalTemplateProps = {
      visible: this.state.showTemplate,
      onOk: this.saveTemplateName,
      onCancel: this.cancelTemplate,
      title: '另存为',
      height: 50,
      width: 380,
      maskClosable: false,
      confirmLoading: loading.effects['limitSetting/addTemplate'] == true,
    };
    return (
      <ModalC {...modalProps}>
        {this.renderTopForm()}
        <CardTreeListC
          onRef={(ref) => {
            this.setState({ TreeList: ref });
          }}
          data={this.state.components}
          conditionOrigin={this.state.conditionOrigin}
          getCurrentNode={this.getCurrentNode}
        />
        {this.state.showTemplate && (
          <ModalC {...modalTemplateProps}>
            <Form ref={this.formRef01}>
              <div className={myStyle.templateName}>
                <InputC form={this.formRef.current} dataIndex='templateName' title='模板名称' initialValue={undefined} rules={[{ required: true, message: '模板名称不能为空' }]} />
              </div>
            </Form>
          </ModalC>
        )}
      </ModalC>
    );
  }
}
export default connect(({ limitSetting, dictionaryM, userM: user, loading }) => ({
  limitSetting,
  dictionaryM,
  user,
  loading,
}))(AddFenzi);
